// -------------------------------------默认的异步操作------------------------------
export function getDirectory(directoryName, successCB) {
	plus.io.requestFileSystem(
		plus.io.PRIVATE_DOC,
		function(fs) {
			//directoryName:可以是一个文件名，如果是路径，则路径上的所有文件夹都会自动创建
			fs.root.getDirectory(directoryName, {
				create: true
			}, successCB, function() {});
			console.log("创建完成.............")
		},
		function(e) {}
	);
}

export function getFile(filePath, successCB) {
	plus.io.requestFileSystem(
		plus.io.PRIVATE_DOC,
		function(fs) {
			//directoryName:可以是一个文件名，如果是路径，则路径上的所有文件夹都会自动创建
			fs.root.getFile(filePath, {
				create: true
			}, successCB, function() {});
			console.log("创建完成.............")
		},
		function(e) {}
	);
}
/**
 * 传入目录dirEntry，如果传了fileName，则删除对应文件，否则目录下所有文件全部删除
 * @param {Object} dirEntry
 * @param {Object} fileName
 */
export function removeFile(dirEntry, fileName) {
	console.log("这里")
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		console.log(fs)
		let entry = dirEntry || fs.root;
		let directoryReader = entry.createReader();
		directoryReader.readEntries(function(entries) {
			console.log(entries)
			for (let i = entries.length - 1; i >= 0; i--) {
				if (fileName) {
					if (fileName === entries[i].name) {
						console.log("删除文件", entries[i].name);
						entries[i].remove();
					}
				} else {
					entries[i].remove();
				}
			}
		});
	});
}


// ----------------------------------------------------------------同步化-操作-----------------------------------------
/**
 * 同步化获取文件,文件不存在会自动创建
 * @param {Object} fileName 可以是文件名，也可以是/路径/文件名
 * @param {Object} dirEntry
 * @return 文件Entry
 */
export async function getFileEntryAsync(fileName, dirEntry) {
	console.log("[getFileEntryAsync]开始执行")
	return new Promise((resolve) => {
		plus.io.requestFileSystem(
			plus.io.PRIVATE_DOC,
			function(fs) {
				console.log("[getFileEntryAsync]fileName is :" + fileName)
				let entry = dirEntry || fs.root;
				entry.getFile(
					fileName, {
						create: true
					},
					function(fileEntry) {
						console.log("[getFileEntryAsync] 执行完成")
						resolve(fileEntry);
					},
					function(ex) {
						console.log(ex)
					}
				);
			}
		);
	})
}

/**
 * 获取文件夹，不存在会自动创建
 * @param {Object} dirName 
 */
export async function getDirEntryAsync(dirName) {
	return new Promise(async (resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			fs.root.getDirectory(dirName, {
				create: true
			}, function(dirEntry) {
				resolve(dirEntry);
			})
		})
	})
}

/**
 * 获取通过fileEntry获取file，不存在会自动创建
 * @param {Object} fileName
 * @param {Object} dirEntry
 */
export async function getFileAsync(fileName, dirEntry) {
	console.log("[getFileAsync]")
	return new Promise(async (resolve) => {
		let fileEntry = await getFileEntryAsync(fileName, dirEntry);
		fileEntry.file(function(file) {
			resolve(file);
		});
	})
}

/**
 * 读取文件中的内容
 * @param {Object} path
 * @param {Object} dirEntry
 */
export async function getFileContextAsync(path, dirEntry) {
	let deffered;
	let fileReader = new plus.io.FileReader();
	fileReader.onloadend = function(evt) {
		deffered(evt.target);
	}
	let file = await getFileAsync(path, dirEntry);
	fileReader.readAsText(file, 'utf-8');
	return new Promise((resolve) => {
		deffered = resolve;
	});
}

/**
 * 向文件中写入数据
 * @param {Object} path 要写入数据的文件的位置
 * @param {Object} fileContext 要写入的内容
 * @param {Object} dirEntry 文件夹，可不写使用默认
 */
export async function writeContextToFileAsync(path, fileContext, dirEntry) {
	let fileEntry = await getFileEntryAsync(path);
	let file = await getFileAsync(path);
	return new Promise((resolve) => {
		fileEntry.createWriter(async writer => {
			// 写入文件成功完成的回调函数
			writer.onwrite = e => {
				console.log("写入数据成功");
				resolve()
			};
			// 写入数据
			writer.write(JSON.stringify(fileContext));
		})
	});
}

/**
 * 判断文件是否存在
 * @param {Object} fileName
 * @param {Object} dirEntry
 */
export async function existFileAsync(fileName, dirEntry) {
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = dirEntry || fs.root;
			let directoryReader = entry.createReader();
			directoryReader.readEntries(function(entries) {
				let isExist = entries.some(entry => entry.name === fileName);
				resolve(isExist);
			});
		});
	})
}

/**
 * 遍历dirEntry，深层次的目录暂不考虑
 * @param {Object} dirEntry
 */
export async function iterateDierctory(dirEntry) {
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = dirEntry || fs.root;
			let directoryReader = entry.createReader();
			directoryReader.readEntries(function(entries) {
				entries.forEach((item, idx, arr) => {
					if (idx === 0) console.log("---------------" + entry.name +
						"目录-----------------");
					console.log(idx + 1, item.name);
					if (idx === arr.length - 1) console.log(
						"---------------end-----------------");
				})
				resolve(entries);
			}, function(e) {
				console.log("Read entries failed: " + e.message);
			});
		});
	})
}
////////////////////////////////////////////////////////
//写入数据
export function writeFile(dirEntry,content) {//dirEntry文件操作对象，content：要写入的内容
	return new Promise(resolve => {
		dirEntry.createWriter(function(writer) { //写入json数据
			writer.onwrite = function(e) {
				resolve({
					code:200,
					msg:"Write data success!",
					info:JSON.stringify(e)
				})
			}
			writer.seek(0);
			writer.write(content);
		});
	})
}
//创建文件
export function createFile(path) {
	return new Promise(resolve => {
		//文件读写是一个异步请求 用promise包起来方便使用时的async+await
		plus.io.requestFileSystem(
			plus.io.PUBLIC_DOCUMENTS,
			fs => {
				fs.root.getFile(path, {
					create:true
				}, fileEntry => {
					fileEntry.file((file) => {
						let fileReader = new plus.io.FileReader();
						fileReader.onloadend = function(evt) {
							console.log(evt)
							resolve({
								code: 200,
								msg:'创建'+file.name+'成功',
								obj:fileEntry,
								info:evt.target.result
							})
						}
						fileReader.readAsText(file, 'utf-8');
						
					});
				}, e => {
					resolve({
						code: 400,
						msg: "getFile failed: " + e.message,
					})
				});
			},
			e => {
				resolve({
					code: 400,
					msg: "getFile failed: " + e.message,
				})
			}
		);
	})
}
// 创建目录 
export function creatDirectory(path, dName) {
	//path:手机基础路径，例file://storage/emulated/0/Android/data/io.dcloud.HBuilder/documents/下,dName:目录名称
	return new Promise(resolve => {
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			entry.getDirectory(dName, {
				create: true,
				exclusive: false
			}, function(dir) {
				resolve({
					code: 200,
					msg: '创建' + dName + '目录成功'
				})
			}, function() {
				resolve({
					code: 400,
					msg: '创建' + dName + '目录失败',
					error: JSON.stringify(e)
				})
			});
		}, function(e) {
			resolve({
				code: 400,
				msg: '创建' + dName + '目录失败',
				error: JSON.stringify(e)
			})
		});
	})

}
// 删除目录
export function delDirectory(path) {
	//path:需要被删除的目录路劲/a/b
	return new Promise(resolve => {
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			entry.removeRecursively(function(entry) {
				console.log("删除目录成功!");
				resolve({
					code: 200,
					msg: '删除目录成功'
				})
			}, function(e) {
				resolve({
					code: 400,
					msg: '删除目录失败',
					error: JSON.stringify(e)
				})
			});
		}, function(e) {
			resolve({
				code: 400,
				msg: '删除目录失败',
				error: JSON.stringify(e)
			})
		});
	})
}
//创建下载任务
export function createTask(netWorkSrc, fileName) {
	//netWorkSrc:下载目标的网络地址链接，fileName:是目录名称
	return new Promise(resolve => {
		let result
		uni.showLoading({
			title: "",
		})
		let dtask = plus.downloader.createDownload(
			netWorkSrc, {
				//1.本地路径开头使用file://;
				//2.Android平台本地绝对路径为"storage/emulated/0",就是用户文件管理器能看到的了;
				//3.创建"xxx"作为文件夹名称，后缀是用于文件命名和格式修改，大家可以使用变量。
				filename: `file://storage/emulated/0/Android/data/io.dcloud.HBuilder/documents/${fileName}/`,
				//利用保存路径，实现下载文件的重命名,最后一个/后面可加变量，这个变量是下载后的文件名称要写后缀，这里我不写，默认使用原文件名
			},
			function(d, status) { //d为下载的文件对象;status下载状态
				if (status == 200) { //下载成功
					result = {
						code: 200,
						msg: '下载成功'
					}
					resolve(result)
					uni.hideLoading()
					//d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
					// let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
					// console.log(fileSaveUrl, d.filename)
					// plus.runtime.openFile(d.filename); //选择软件打开文件
				} else { //下载失败
					plus.downloader.clear(); //清除下载任务
					result = {
						code: 200,
						msg: '下载失败'
					}
					resolve(result)
					uni.hideLoading()
				}
			}
		);
		dtask.start(); //启用

	})

}
//查看目录下的某个指定文件
export function getFileData(path) {
	return new Promise(resolve => {
		//文件读写是一个异步请求 用promise包起来方便使用时的async+await
		plus.io.requestFileSystem(
			plus.io.PUBLIC_DOCUMENTS,
			fs => {
				fs.root.getFile(path, {
					create: false
				}, fileEntry => {
					fileEntry.file((file) => {
						console.log("文件大小:" + file.size + '-- 文件名:' + file.name);
						//创建读取文件对象
						let fileReader = new plus.io.FileReader();
						//以文本格式读取文件数据内容
						fileReader.readAsText(file, 'utf-8');
						//文件读取操作完成时的回调函数
						fileReader.onloadend = (evt) => {
							console.log(JSON.parse(evt.target.result),
								'JSON.parse(evt.target.result)')
							resolve({
								code: 200,
								msg: '获取信息成功',
								result: JSON.parse(evt.target.result)
							})
						}
					});
				}, e => {
					resolve({
						code: 400,
						msg: "getFile failed: " + e.message,
					})
				});
			},
			e => {
				resolve({
					code: 400,
					msg: "getFile failed: " + e.message,
				})
			}
		);
	})
}
//查看我们新建的目录下的所有文件,或者删除指定文件
export function getFileList(path) {
	//path:查询目录，例/a/c/b
	uni.showLoading({
		title: "",
	})
	return new Promise((resolve) => {
		plus.io.resolveLocalFileSystemURL(path,
			function(entry) {
				var directoryReader = entry.createReader(); //获取读取目录对象
				directoryReader.readEntries(function(entries) { //历遍子目录即可.
						var entries_con = [];
						var i;
						if (entries.length > 0) {
							for (i = 0; i < entries.length; i++) {
								entries_con.push({
									name: entries[i].name,
									fullPath: entries[i].fullPath
								})
							}

						}
						resolve({
							code: 200,
							msg: '查询成功',
							data: [...entries_con]
						})
						uni.hideLoading()
					},
					function(e) {
						resolve({
							code: 400,
							msg: '访问目录失败',
							error: JSON.stringify(e)
						})
						uni.hideLoading()
					}
				);
			},
			function(e) {
				resolve({
					code: 400,
					msg: '访问目录失败',
					error: JSON.stringify(e)
				})
				uni.hideLoading()
			}
		)
	})
}
export function delFileList(path, isDelete = false, fileName) {
	//path:需要删除文件的父级目录，isDelete:是否全删,默认为false,fileName需要删除的文件名a.mp3等
	uni.showLoading({
		title: "",
	})
	return new Promise((resolve) => {
		plus.io.resolveLocalFileSystemURL(path,
			function(entry) {
				var directoryReader = entry.createReader(); //获取读取目录对象
				directoryReader.readEntries(function(entries) { //历遍子目录即可.
						var entries_con = [];
						var i;
						if (isDelete) { //全删
							for (i = 0; i < entries.length; i++) {
								entries[i].remove();
							}
							resolve({
								code: 200,
								msg: '删除成功',
							})
						} else { //单删
							for (i = 0; i < entries.length; i++) {
								if (entries[i].name == fileName) {
									entries[i].remove();
								}
							}
							resolve({
								code: 200,
								msg: '删除成功',
							})
						}
						uni.hideLoading()
					},
					function(e) {
						resolve({
							code: 400,
							msg: '访问目录失败',
							error: JSON.stringify(e)
						})
						uni.hideLoading()
					}
				);
			},
			function(e) {
				resolve({
					code: 400,
					msg: '访问指定目录失败',
					error: JSON.stringify(e)
				})
				uni.hideLoading()
			}
		)
	})
}
// 多文件拷贝
export function multifileCopyFile(path, targetFile) {
	//path:要拷贝的文件目录路径/a/b/c/注意加'/',targetFile:要拷贝的目标目录路径/a/b/c
	return new Promise((resolve) => {
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			var f = entry.createReader();
			f.readEntries(async function(en) {
					var succeed = [] //成功拷贝的文件
					var failed = [] //失败文件
					for (let k = 0; k < en.length; k++) {
						var res = await copyFile(en[k].fullPath, targetFile);
						if (res.code == 200) {
							succeed.push(res.fullPath)
						} else {
							failed.push(res.fullPath)
						}
					}
					resolve({
						code: 200,
						msg: '成功与失败集合',
						succeedData: JSON.stringify(succeed),
						failedData: JSON.stringify(failed)
					})
				},
				function(e) {
					resolve({
						code: 400,
						msg: '读取路径失败',
						error: JSON.stringify(e)
					})
				});
		}, function(e) {
			resolve({
				code: 400,
				msg: '读取路径失败',
				error: JSON.stringify(e)
			})
		});
	})

}
// 单文件拷贝
export function copyFile(file1, file2) {
	//file1:要拷贝的文件路径/a/b.mp3,file2:拷贝到哪个目录/a/b
	return new Promise((resolve) => {
		plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
			fs.root.getFile(file1, {
				create: true
			}, function(fileEntry) {
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs1) {
					fs.root.getDirectory(file2, {
						create: true,
						exclusive: false
					}, function(fileEntry1) {
						fileEntry.copyTo(fileEntry1, null, function(entry) {
							resolve({
								code: 200,
								msg: "拷贝文件成功",
								fullPath: entry.fullPath
							})
						}, function(e) {
							resolve({
								code: 400,
								msg: '拷贝出错',
								fullPath: file1, //拷贝失败文件路径
								error: JSON.stringify(e)
							})
						});
					});
				});
			});
		});
	})
}
//压缩文件
export function zipCompress(path, targetZip) {
	//需要被压缩的目录路径，例_doc/temp/,targetZip:生成的压缩包文件地址,例_doc/temp.zip
	return new Promise((resolve) => {
		plus.zip.compress(path, targetZip,
			function() {
				resolve({
					code: 200,
					msg: '压缩成功',
					fullPath: targetZip
				})
			},
			function(error) {
				resolve({
					code: 400,
					msg: '压缩失败'
				})
			});
	})

}
/* 调用例子
this.DIR_NAME = 'test'
fileName = 'test.json'
filePath = '_doc/test/test.json'
let dirEntry = await this.getDirEntry(this.DIR_NAME); //创建、获取文件夹
let fileEntry = await this.getFileEntry(fileName, dirEntry); // 创建、获取文件
let {result:content} = await this.getFileContext(filePath); // 获取文件的内容
let trajectory = JSON.parse(content||"[]");
trajectory.push({lat, lng});
fileEntry.createWriter(function(writer){
	writer.seek(0);
	writer.write(JSON.stringify(trajectory));
}); */
